<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 行业配置管理
 */
class IndustryConfig extends Backend
{
    protected $model = null;
    protected $noNeedRight = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\IndustryConfig;
    }

    /**
     * 检查字段唯一性
     */
    public function check_unique()
    {
        // 支持GET和POST两种方式获取参数
        $field = $this->request->param('field') ?: $this->request->post('field');
        $value = $this->request->param('value') ?: $this->request->post('value');
        $id = $this->request->param('id', 0) ?: $this->request->post('id', 0);
        
        // 如果value为空，尝试从POST的row数组中获取
        if (empty($value)) {
            $postData = $this->request->post();
            if (isset($postData['row']) && isset($postData['row'][$field])) {
                $value = $postData['row'][$field];
            }
        }
        
        // 调试信息
        \think\Log::info('check_unique params: ' . json_encode([
            'field' => $field,
            'value' => $value,
            'id' => $id,
            'get' => $this->request->get(),
            'post' => $this->request->post()
        ]));
        
        if (empty($field) || empty($value)) {
            $this->error('参数错误: field=' . $field . ', value=' . $value);
        }
        
        $where = [$field => $value];
        if ($id > 0) {
            $where['id'] = ['neq', $id];
        }
        
        $exists = $this->model->where($where)->find();
        
        if ($exists) {
            $this->error('该值已存在');
        } else {
            $this->success('验证通过');
        }
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // JSON字段处理
                $jsonFields = ['data_template', 'field_config', 'process_config', 'algorithm_config', 'ui_config'];
                foreach ($jsonFields as $field) {
                    if (isset($params[$field]) && is_array($params[$field])) {
                        $params[$field] = json_encode($params[$field], JSON_UNESCAPED_UNICODE);
                    }
                }
                
                $result = false;
                Db::startTrans();
                try {
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // JSON字段处理
                $jsonFields = ['data_template', 'field_config', 'process_config', 'algorithm_config', 'ui_config'];
                foreach ($jsonFields as $field) {
                    if (isset($params[$field]) && is_array($params[$field])) {
                        $params[$field] = json_encode($params[$field], JSON_UNESCAPED_UNICODE);
                    }
                }
                
                $result = false;
                Db::startTrans();
                try {
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // JSON字段解析
        $jsonFields = ['data_template', 'field_config', 'process_config', 'algorithm_config', 'ui_config'];
        foreach ($jsonFields as $field) {
            if (!empty($row[$field])) {
                $row[$field] = json_decode($row[$field], true);
            }
        }
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $list = $this->model->where($pk, 'in', $ids)->select();
            
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $item) {
                    $count += $item->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 激活行业配置
     */
    public function activate($ids = "")
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        Db::startTrans();
        try {
            // 取消其他行业的激活状态
            Db::name('scanwork_industry_config')->where('id', 'neq', $ids)->update(['is_active' => 0]);
            
            // 激活当前行业
            $row->is_active = 1;
            $row->save();
            
            // 应用行业配置
            $this->applyIndustryConfig($row);
            
            Db::commit();
            $this->success('行业配置已激活');
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 行业切换页面
     */
    public function switch()
    {
        if ($this->request->isPost()) {
            $industryCode = $this->request->post('industry_code');
            if (empty($industryCode)) {
                $this->error('请选择行业');
            }
            
            // 验证行业是否存在
            $industry = $this->model->where('industry_code', $industryCode)->find();
            if (!$industry) {
                $this->error('选择的行业不存在');
            }
            
            // 保存到session
            session('current_industry', $industryCode);
            session('current_industry_name', $industry['industry_name']);
            
            $this->success('行业切换成功', '', ['industry_code' => $industryCode, 'industry_name' => $industry['industry_name']]);
        }
        
        // 获取所有行业配置
        $list = $this->model->where('status', 'normal')->order('sort asc, id asc')->select();
        $currentIndustry = session('current_industry');
        $currentIndustryName = session('current_industry_name');
        
        // 如果没有设置当前行业，默认使用第一个启用的行业
        if (empty($currentIndustry) && !empty($list)) {
            $currentIndustry = $list[0]['industry_code'];
            $currentIndustryName = $list[0]['industry_name'];
            session('current_industry', $currentIndustry);
            session('current_industry_name', $currentIndustryName);
        }
        
        $this->view->assign('list', $list);
        $this->view->assign('current_industry', $currentIndustry);
        $this->view->assign('current_industry_name', $currentIndustryName);
        
        return $this->view->fetch();
    }

    /**
     * 应用行业配置
     */
    private function applyIndustryConfig($industryConfig)
    {
        // 1. 激活自定义字段
        if (!empty($industryConfig->field_config)) {
            $fieldConfig = json_decode($industryConfig->field_config, true);
            if ($fieldConfig && is_array($fieldConfig)) {
                foreach ($fieldConfig as $field) {
                    // 检查字段是否已存在
                    $exists = Db::name('scanwork_custom_field')
                        ->where('industry_code', $industryConfig->industry_code)
                        ->where('field_name', $field['field_name'])
                        ->find();
                    
                    if (!$exists) {
                        Db::name('scanwork_custom_field')->insert(array_merge($field, [
                            'industry_code' => $industryConfig->industry_code,
                            'createtime' => time(),
                            'updatetime' => time()
                        ]));
                    }
                }
            }
        }
        
        // 2. 激活排程规则
        if (!empty($industryConfig->algorithm_config)) {
            $algorithmConfig = json_decode($industryConfig->algorithm_config, true);
            if ($algorithmConfig && isset($algorithmConfig['rules']) && is_array($algorithmConfig['rules'])) {
                foreach ($algorithmConfig['rules'] as $rule) {
                    // 检查规则是否已存在
                    $exists = Db::name('scanwork_schedule_rule')
                        ->where('rule_code', $rule['rule_code'])
                        ->find();
                    
                    if (!$exists) {
                        Db::name('scanwork_schedule_rule')->insert(array_merge($rule, [
                            'industry_code' => $industryConfig->industry_code,
                            'createtime' => time(),
                            'updatetime' => time()
                        ]));
                    }
                }
            }
        }
    }
}

